
import { createContext, useContext, useState, useEffect } from 'react';
// 1. 创建 AuthContext
const AuthContext = createContext(null);
// 2. 权限提供者组件
export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  // 初始化：从 localStorage 读取登录状态
  useEffect(() => {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
  }, []);

  // 登录：存储用户信息到本地存储和状态
  const login = (userInfo) => {
    setUser(userInfo);
    localStorage.setItem('user', JSON.stringify(userInfo));
  };

  // 退出：清除用户信息
  const logout = () => {
    setUser(null);
    localStorage.removeItem('user');
  };

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

// 3. 自定义 Hook：快速获取权限信息
export const useAuth = () => useContext(AuthContext);